package ru.uskov.trainer;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.uskov.trainer.datastore.IContext;
import ru.uskov.trainer.datastore.UserIdentifyer;
import ru.uskov.trainer.datastore.impl.ContextGenerator;
import ru.uskov.trainer.model.IProductItem;
import ru.uskov.trainer.model.UserAuthData;

public class MainPage extends HttpServlet {
  public final static String CODEPAGE = "CP1251";
  private static final long serialVersionUID = -4534261073600409012L;
  public static final String USER_ID_COOKIE_NAME = "personal_trainer_uid";
  public static final String USER_ID_COOKIE_PWD = "personal_trainer_pwd";

  private UserAuthData enshureCookiesSet(UserAuthData uad, HttpServletResponse response) {
    // setting cookie

    UserAuthData userId = ContextGenerator.getInstance().generateNewUserId();
    response.addCookie(new Cookie(USER_ID_COOKIE_NAME, userId.getId()));
    response.addCookie(new Cookie(USER_ID_COOKIE_PWD, userId.getPwd()));
    return userId;

  }

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    if (request.getParameter("id") != null) {
      doPost(request, response);
      return;
    }
    // IE hack! Important! Allows setting cookies
    response.addHeader("P3P", "IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT");

    UserAuthData uid = Utils.getUserId(request.getCookies());
    if ((uid == null) || (!uid.userIdIsCorrect())) {
      uid = enshureCookiesSet(uid, response);
    }

    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    InputStream templateIS = MainPage.class.getResourceAsStream("/mainpage.vm");
    Reader reader = new InputStreamReader(templateIS, CODEPAGE);
    // /
    Map<String, Object> map = new HashMap<String, Object>();
    List<IProductItem> selectedItems = new ArrayList<IProductItem>();
    if (uid.userIdIsCorrect()) {
      selectedItems = ContextGenerator.getInstance().getUserData(uid).getProducts();
    }
    map.put("selectedProducts", selectedItems);
    IContext context = ContextGenerator.getInstance();
    map.put("productGroups", context.getGroups());
    map.put("context", ContextGenerator.getInstance());
    map.put("summ", context.getSum(selectedItems));
    // /
    PrintWriter out = response.getWriter();
    out.println(Utils.compileTemplate(reader, map));
    reader.close();
    out.flush();

  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    ServletOutputStream sos = response.getOutputStream();
    sos.println("Quantity: " + request.getParameter("quantity"));
    sos.println("Product: " + request.getParameter("product"));
    sos.println("ProductGroup: " + request.getParameter("productsGroup"));
    sos.println("hidden field: " + request.getParameter("id"));

    // doGet(request, response);
  }
}